package com.codyy.lib_common.leak

import android.content.Context
import android.os.Build
import android.view.inputmethod.InputMethodManager
import java.lang.reflect.Field

/**
 * 修复华为手机输入法引起的内存泄漏
 * fix:Description: HUAWEI added a mLastSrvView field to InputMethodManager that leaks a reference to the last served view.
 * https://www.jianshu.com/p/95242060320f
 */
object FixMemLeak {
    private var field: Field? = null
    private var hasField = true
    private const val BRAND = "HUAWEI"

    /**
     * 华为手机6.0及以上版本出现mLastSrvView内存泄漏通过反射关闭
     */
    fun fixLeak(context: Context) {
        if (BRAND != Build.BRAND && Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return
        }
        if (!hasField) {
            return
        }
        val imm =
            context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        val arr = arrayOf("mLastSrvView")
        for (param in arr) {
            try {
                if (field == null) {
                    field = imm.javaClass.getDeclaredField(param)
                }
                if (field == null) {
                    hasField = false
                }
                if (field != null) {
                    field!!.isAccessible = true
                    field!![imm] = null
                }
            } catch (t: Throwable) {
                t.printStackTrace()
            }
        }
    }
}